package org.droidplanner.android.zz;

import android.graphics.Color;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.Polygon;
import com.baidu.mapapi.map.PolygonOptions;
import com.baidu.mapapi.map.Polyline;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.map.Stroke;
import com.baidu.mapapi.map.TextOptions;
import com.baidu.mapapi.map.UiSettings;
import com.baidu.mapapi.model.LatLng;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.droidplanner.android.R;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 遥控器规划地块
 */
public class HandControlPlanActivity extends BaseActivity {
    private MapView mMapView;
    private BaiduMap mBaiduMap;
    private LocationClient locationClient;
    private ImageView ivLocation;
    private BitmapDescriptor markgreen = BitmapDescriptorFactory.fromResource(R.drawable.d);
    private BitmapDescriptor markred = BitmapDescriptorFactory.fromResource(R.drawable.d1);
    private ArrayList<LatLng> planPointsList = new ArrayList<>();
    private ArrayList<LatLng> passPointsList = new ArrayList<>();
    private ArrayList<ArrayList<LatLng>> passPointsAllList = new ArrayList<>();
    private RadioButton rbPlan;
    private RadioButton rbPass;
    private boolean isPlanOver = false;
    private ImageView ivChoosePoint;

    @Override
    public int getLayoutId() {
        return R.layout.activity_hand_control_plan;
    }

    @Override
    public void initView() {
        mMapView = (MapView) findViewById(R.id.map);
        ivLocation = (ImageView) findViewById(R.id.iv_location);
        ivChoosePoint = (ImageView) findViewById(R.id.iv_choose_point);
        mBaiduMap = mMapView.getMap();
        rbPlan = (RadioButton) findViewById(R.id.rb_plan);
        rbPass = (RadioButton) findViewById(R.id.rb_pass);
        rbPlan.setChecked(true);
    }

    @Override
    public void initData() {
        mBaiduMap.setMyLocationEnabled(true);  //开启定位图层
        try {
            initLocation();
        } catch (Exception e) {
            Log.v("百度地图", "异常=" + e.toString());
        }
        planMapPoint();
    }

    @Override
    public void initListeners() {
        mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            /**
             * 单击地图
             */
            @Override
            public void onMapClick(LatLng point) {
                //"单击地图";
                drawMap(point);
            }

            /**
             * 单击地图中的POI点
             * @return
             */
            @Override
            public boolean onMapPoiClick(MapPoi poi) {
                //"单击POI点";
                //ToastUtil.showToast("请点击非POI点");
                //"单击地图";
                LatLng point = poi.getPosition();
                drawMap(point);
                return false;
            }
        });


    }

    private void drawMap(LatLng point) {
        boolean rbPlanState = rbPlan.isChecked();
        boolean rbPassState = rbPass.isChecked();
        //地块
        if (rbPlanState) {
            if (isPlanOver) {
                Toast.makeText(mContext, "请先保存地块", Toast.LENGTH_SHORT).show();
                return;
            }

            MarkerOptions ooA = new MarkerOptions().position(point).icon(markgreen);
            mBaiduMap.addOverlay(ooA);
            planPointsList.add(point);

            if (planPointsList.size() > 1) {
                // 覆盖物参数配置
                OverlayOptions ooPolyline = new PolylineOptions()
                        .width(4)// 设置折线线宽， 默认为 5， 单位：像素
                        .color(Color.parseColor("#41F18D"))//  折线颜色。注意颜色值得格式为：0xAARRGGBB，透明度值在前
                        .points(planPointsList);// 折线坐标点列表 数目[2,10000]，且不能包含 null
                // 添加覆盖物
                Overlay mPolyline = (Polyline) mBaiduMap.addOverlay(ooPolyline);
            }
            //写文字
            int size = planPointsList.size();
            OverlayOptions mTextOptions = new TextOptions()
                    .text(size + "") //文字内容
                    .bgColor(Color.parseColor("#00000000")) //背景色
                    .fontSize(40) //字号
                    .fontColor(Color.parseColor("#FFFF00FF")) //文字颜色
                    .rotate(0) //旋转角度
                    .position(point);
            Overlay mText = mBaiduMap.addOverlay(mTextOptions);
        }

        //障碍物
        if (rbPassState) {
            MarkerOptions ooA = new MarkerOptions().position(point).icon(markred);
            mBaiduMap.addOverlay(ooA);
            passPointsList.add(point);

            if (passPointsList.size() > 1) {
                // 覆盖物参数配置
                OverlayOptions ooPolyline = new PolylineOptions()
                        .width(4)// 设置折线线宽， 默认为 5， 单位：像素
                        .color(Color.parseColor("#e3170d"))//  折线颜色。注意颜色值得格式为：0xAARRGGBB，透明度值在前
                        .points(passPointsList);// 折线坐标点列表 数目[2,10000]，且不能包含 null
                // 添加覆盖物
                Overlay mPolyline = (Polyline) mBaiduMap.addOverlay(ooPolyline);
            }

            //写文字
            int size = passPointsList.size();
            OverlayOptions mTextOptions = new TextOptions()
                    .text(size + "") //文字内容
                    .bgColor(Color.parseColor("#00000000")) //背景色
                    .fontSize(40) //字号
                    .fontColor(Color.parseColor("#FF912CEE")) //文字颜色
                    .rotate(0) //旋转角度
                    .position(point);
            Overlay mText = mBaiduMap.addOverlay(mTextOptions);
        }


    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_back:
                finish();
                break;
            case R.id.iv_location:
                Log.v("百度地图", "click");
                Toast.makeText(mContext, "重新定位", Toast.LENGTH_SHORT).show();
                try {
                    initLocation();
                } catch (Exception e) {
                    Log.v("百度地图", "异常=" + e.toString());
                }
                break;
            case R.id.iv_choose_point:    //添加定位当前点
                choosePoint();
                break;
            case R.id.tv_clear:    //清除规划
                clearMap();
                break;
            case R.id.tv_sure_plan: //确定规划
                surePlanPoint();
                break;
            case R.id.tv_save_plan://保存规划地图
                savePlanPint();
                break;
        }
    }

    //添加当前位置到规划中
    private void choosePoint() {
        BDLocation lastKnownLocation = locationClient.getLastKnownLocation();
        LatLng point = new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
        drawMap(point);
    }

    //保存规划地块
    private void savePlanPint() {
        if (!isPlanOver) {
            Toast.makeText(mContext, "请先规划完成再保存", Toast.LENGTH_SHORT).show();
            return;
        }
        BaseDialog baseDialog = new BaseDialog(mContext, R.layout.dialog_save_plan);
        baseDialog.show();
        TextView tvContent = (TextView) baseDialog.findViewById(R.id.tv_plan_content);
        EditText etPlanName = (EditText) baseDialog.findViewById(R.id.et_plan_name);

        tvContent.setText("规划地块面积: " + " 平方米" + "\n" + "亩数: " + " 亩");

        baseDialog.findViewById(R.id.tv_cancle).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                baseDialog.dismiss();
            }
        });
        baseDialog.findViewById(R.id.tv_sure).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String name = etPlanName.getText().toString().trim();
                if (TextUtils.isEmpty(name)) {

                    Toast.makeText(mContext, "请输入地块名称", Toast.LENGTH_SHORT).show();

                    return;
                }

                String areaString = SpEasy.getData(SpName.area_detail, "");
                ArrayList<PlanAreaBean> areaList;
                if (TextUtils.isEmpty(areaString)) {
                    areaList = new ArrayList<>();
                } else {
                    Type type = new TypeToken<ArrayList<PlanAreaBean>>() {
                    }.getType(); // 指定目标类型
                    areaList = new Gson().fromJson(areaString, type);
                }

                PlanAreaBean planAreaBean = new PlanAreaBean();
                planAreaBean.setName(name);
                planAreaBean.setPlanMi("1");
                planAreaBean.setPlanMu("1");
                planAreaBean.setId(System.currentTimeMillis() + "");
                planAreaBean.setPlanPointsList(planPointsList);
                planAreaBean.setPassPointsAllList(passPointsAllList);
                areaList.add(planAreaBean);
                SpEasy.saveData(SpName.area_detail, new Gson().toJson(areaList));
                baseDialog.dismiss();
            }
        });
        Log.v("路径是", Arrays.asList(planPointsList).toString());
    }

    //确定规划点
    private void surePlanPoint() {
        boolean rbPlanState = rbPlan.isChecked();
        boolean rbPassState = rbPass.isChecked();
        //障碍物
        if (rbPassState) {
            if (passPointsList.size() < 3) {
                Toast.makeText(mContext, "至少需要三个点", Toast.LENGTH_SHORT).show();

                return;
            }
            passPointsAllList.add(new ArrayList<>(passPointsList));

            OverlayOptions ooPolygon = new PolygonOptions()
                    .points(passPointsList)// 设置多边形坐标点列表
                    .stroke(new Stroke(4, Color.parseColor("#e3170d")))// 设置多边形边框信息
                    .fillColor(Color.parseColor("#e3170d"));// 设置多边形填充颜色
            // 添加覆盖物
            Overlay mPolygon = (Polygon) mBaiduMap.addOverlay(ooPolygon);

            passPointsList.clear();
        }

        //地块
        if (rbPlanState) {
            if (isPlanOver) {
                Toast.makeText(mContext, "至少需要三个点", Toast.LENGTH_SHORT).show();
                return;
            }

            if (planPointsList.size() < 3) {
                Toast.makeText(mContext, "至少需要三个点", Toast.LENGTH_SHORT).show();
                return;
            }

            OverlayOptions ooPolygon = new PolygonOptions()
                    .points(planPointsList)// 设置多边形坐标点列表
                    .stroke(new Stroke(4, Color.parseColor("#41F18D")))// 设置多边形边框信息
                    .fillColor(Color.parseColor("#8841F18D"));// 设置多边形填充颜色
            // 添加覆盖物
            Overlay mPolygon = (Polygon) mBaiduMap.addOverlay(ooPolygon);

            isPlanOver = true;

            //让障碍物放在最上面
            for (int i = 0; i < passPointsAllList.size(); i++) {
                ArrayList<LatLng> latLngs = passPointsAllList.get(i);

                Log.v("百度地图", Arrays.asList(latLngs).toString());

                OverlayOptions ooPolygonAgain = new PolygonOptions()
                        .points(latLngs)// 设置多边形坐标点列表
                        .stroke(new Stroke(4, Color.parseColor("#e3170d")))// 设置多边形边框信息
                        .fillColor(Color.parseColor("#88e3170d"));// 设置多边形填充颜色
                // 添加覆盖物
                Overlay mPolygonAgain = (Polygon) mBaiduMap.addOverlay(ooPolygonAgain);
            }
        }
    }

    /**
     * 初始化定位参数配置
     */

    private void initLocation() throws Exception {
        setMapType();
        locationClient = new LocationClient(this);
        LocationClientOption option = new LocationClientOption();
        option.setIsNeedAddress(true);
        option.setOpenGps(true);
        option.setCoorType("bd09ll");
//        option.setScanSpan(1000);
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);  //// 可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        locationClient.setLocOption(option);
        MyLocationListener myLocationListener = new MyLocationListener();
        locationClient.registerLocationListener(myLocationListener);
        locationClient.start();
    }

    //设置地图样式
    private void setMapType() {
        UiSettings uiSettings = mBaiduMap.getUiSettings();
        uiSettings.setRotateGesturesEnabled(false);//是否允许地图旋转手势，默认允许
        uiSettings.setScrollGesturesEnabled(true); //是否允许拖拽手势，默认允许
        uiSettings.setOverlookingGesturesEnabled(true); //是否允许俯视图手势，默认允许
        uiSettings.setZoomGesturesEnabled(true); //是否可以缩放
        uiSettings.setCompassEnabled(true); //是否开启指南针

        //普通地图 卫星地图
        mBaiduMap.setMapType(SpEasy.getData(SpName.map_type, BaiduMap.MAP_TYPE_NORMAL));   //地图模式，默认为普通地图 BaiduMap.MAP_TYPE_NORMAL  MAP_TYPE_SATELLITE
        mMapView.showZoomControls(false); //缩放按钮
    }

    /**
     * 实现定位回调
     */
    public class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            Log.v("百度地图", "location=" + location);
            //获取纬度信息
            double latitude = location.getLatitude();
            //获取经度信息
            double longitude = location.getLongitude();
            //获取定位精度，默认值为0.0f
            float radius = location.getRadius();
            //获取经纬度坐标类型，以LocationClientOption中设置过的坐标类型为准
            String coorType = location.getCoorType();
            //获取定位类型、定位错误返回码，具体信息可参照类参考中BDLocation类中的说明
            int errorCode = location.getLocType();

            Log.v("百度地图", "定位回调" + "latitude=" + latitude + "  longitude=" + longitude + "  radius=" + radius + "   coorType=" + coorType + "   errorCode=" + errorCode);
            MyLocationData locData = new MyLocationData.Builder().accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(location.getDirection()).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            // 设置定位数据
            mBaiduMap.setMyLocationData(locData);

            //设置当前位置在屏幕中心
            LatLng latLng = new LatLng(location.getLatitude(),
                    location.getLongitude());
            MapStatus.Builder builder = new MapStatus.Builder();
            builder.target(latLng).zoom(18.0f);
            mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
        }
    }

    public void clearMap() {
        planPointsList.clear();
        passPointsList.clear();
        passPointsAllList.clear();
        mBaiduMap.clear();
        isPlanOver = false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时必须调用mMapView. onResume ()
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时必须调用mMapView. onPause ()
        mMapView.onPause();
        locationClient.stop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时必须调用mMapView.onDestroy()
        mMapView.onDestroy();
    }

    //[[latitude: 30.27901820737943, longitude: 120.12979381485914,
    // latitude: 30.27893030036089, longitude: 120.13117410192355,
    // latitude: 30.27830741398459, longitude: 120.13082975365495,
    // latitude: 30.278647741529905, longitude: 120.12932069757689]]


    private void planMapPoint() {
        // 假设你已经有了多边形的顶点列表
        List<LatLng> polygonPoints = new ArrayList<>();
        polygonPoints.add(new LatLng(30.27901820737943, 120.12979381485914));
        polygonPoints.add(new LatLng(30.27830741398459, 120.13082975365495));
        polygonPoints.add(new LatLng(30.27893030036089, 120.13117410192355));
        polygonPoints.add(new LatLng(30.278647741529905, 120.12932069757689));

    }
}